/**
 * 统一登录处理
 * 账号密码登录、扫脸登录、微信验证登录
 * 登录成功后统一跳转到主页
 * 首次登录统一跳转到个人信息配置页
 * 登录有冲突时统一提示登录冲突，确认后，带原参数二次发起登录请求
 */
import { useCounterStore } from "./../stores/counter";
const counterStore = useCounterStore();
import { createDiscreteApi, useDialog } from "naive-ui";
const { message } = createDiscreteApi(["message"]);
const { dialog } = createDiscreteApi(["dialog"]);
// const dialog = useDialog()
export default function unifiedLogin(
  router: any,
  params: any,
  LOG_API: any,
  callbacks: any
) {
  const {
    resp_get_cb = (res: any) => {}, // 获取登录结果回调
    resp_succ_cb = (res: any) => {}, // 登录成功回调
    resp_accept_cb = (res: any) => {}, // 登录成功，需要接受协议回调
    resp_fail_cb = (res: any) => {}, // 登录失败回调
    force_login_ok_cb = (res: any) => {}, // 强制登录点击确定时的回调
    force_login_cancel_cb = (res: any) => {}, // 强制登录点击取消时的回调
    err_cb = (err: any) => {}, // 登录报错时的回调
  } = callbacks;

  LOG_API({ params: JSON.stringify(params) })
    .then((res: any) => {
      resp_get_cb(res);
      console.log("登录返回结果", params, res);
      if (res.stacode == 200) {
        resp_succ_cb(res);
        const { login_conflict } = res.data;
        if (login_conflict) {
          dialog.warning({
            title: "账号已在其他设备登录",
            content: "下线其他设备，并在当前设备登录？",
            positiveText: "确定",
            negativeText: "取消",
            onPositiveClick: () => {
              force_login_ok_cb(res);
              // 用相同参数重新登录
              LOG_API({
                params: JSON.stringify({ ...params, login_force: true }),
              }).then((next_res: any) => {
                if (next_res.stacode == 200) {
                  counterStore.setToken(next_res.data.token);
                  counterStore.setInfo(next_res.data.userinfo);
                  counterStore.login();
                  if (next_res.data.reset_password) {
                    counterStore.setInitialUser();
                    router.push("setting");
                  } else {
                    counterStore.setNotInitialUser();
                    router.push("application");
                  }
                } else {
                  message.error(next_res.message);
                }
              });
            },
            onNegativeClick: () => {
              force_login_cancel_cb(res);
            },
          });
          return;
        }
        const { token, userinfo, reset_password } = res.data;
        // 不冲突时的登录流程
        counterStore.setToken(token);
        counterStore.setInfo(userinfo);
        counterStore.login();
        if (reset_password) {
          counterStore.setInitialUser();
          router.push("setting");
        } else {
          counterStore.setNotInitialUser();
          router.push("application");
        }
      } else if (res.stacode == 202) {
        resp_accept_cb(res);
      } else {
        message.error(res.message);
        resp_fail_cb(res);
      }
    })
    .catch((err: any) => {
      err_cb(err);
    });
}
